package com.yinhai.message.implement.websocket;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.web.socket.server.support.WebSocketHandlerMapping;

import javax.annotation.Resource;

/**
 * Created by yanglq on 2018/4/3 0003.
 */
@Configuration
//@EnableWebMvc
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(chatMessageHandler(),"/webSocketServer").addInterceptors(new ChatHandshakeInterceptor()).setAllowedOrigins("*");
        registry.addHandler(chatMessageHandler(), "/sockjs/webSocketServer").addInterceptors(new ChatHandshakeInterceptor()).setAllowedOrigins("*").withSockJS();

    }

    @Bean
    public TextWebSocketHandler chatMessageHandler(){
        return new ChatMessageHandler();
    }

    /**
     * 获取 org.springframework.web.socket.config.annotation.WebSocketConfigurationSupport
     * 注册的 webSocketHandlerMapping
     * 修改urlPathHelper 的 AlwaysUseFullPath 属性
     * 否则无法匹配 spring mvc 过滤的 sockjs/*  全路径
     */
    @Resource(name="webSocketHandlerMapping")
    public void setHandlerMapping(WebSocketHandlerMapping handlerMapping) {
        handlerMapping.setAlwaysUseFullPath(true);
    }

    /**
     *  ie8 使用 sockjs  需要web.xml 中加入 <async-supported>true</async-supported>
     */
}
